# 估计交通流量(汽车通过数)
import numpy as np
from sklearn import preprocessing
from sklearn.svm import SVR

input_file = "F:/python学习资料/Python-Machine-Learning-Cookbook-master/" \
             "Chapter03/traffic_data.txt"

# 读取数据
X = []
count = 0
with open(input_file,'r') as f:
    for line in f.readlines():
        data = line[:-1].split(",")
        X.append(data)

X = np.array(X)

# 对数据编码
label_encoder = []
X_encoded = np.empty(X.shape)
for i,item in enumerate(X[0]):
    if item.isdigit():
        X_encoded[:,i] = X[:,i]
    else:
        label_encoder.append(preprocessing.LabelEncoder())
        X_encoded[:,i] = label_encoder[-1].fit_transform(X[:,i])

X = X_encoded[:,:-1].astype(int)
y = X_encoded[:,-1].astype(int)

from sklearn.model_selection import train_test_split
import sklearn.metrics as sm

X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=2,test_size=0.25)

# 构建SVR
params = {'kernel':'rbf','C':10,'epsilon':0.2}
regressor = SVR(**params)
regressor.fit(X_train,y_train)
print("SVR精度:{:.3f}".format(regressor.score(X_test,y_test)))
print(sm.mean_squared_error(y_test,regressor.predict(X_test)))

# 构建线性模型
from sklearn.linear_model import Ridge
ridge = Ridge()
ridge.fit(X_train,y_train)
print("岭回归精度:{:.3f}".format(ridge.score(X_test,y_test)))
print(sm.mean_squared_error(y_test,ridge.predict(X_test)))
# 决策树回归
from sklearn.tree import DecisionTreeRegressor
dr_regressor = DecisionTreeRegressor()
dr_regressor.fit(X_train,y_train)
print("决策回归树精度:{:.3f}".format(dr_regressor.score(X_test,y_test)))
print(sm.mean_squared_error(y_test,dr_regressor.predict(X_test)))

# 在一个数据点上做测试
input_data = ['Tuesday','13:35','San Francisco','yes']
input_data_encoded = [-1]*len(input_data)
count = 0
for i ,item in enumerate(input_data):
    if item.isdigit():
        input_data_encoded[i] = int(input_data[i])
    else:
        input_data_encoded[i] = int(label_encoder[count].transform([input_data[i]]))
        count = count+1

input_data_encoded= np.array(input_data_encoded)

print("打印预测")
# 预测并打印
print("SVR:",int(regressor.predict([input_data_encoded])[0]))
print("Ridge:",int(ridge.predict([input_data_encoded])[0]))
print("决策回归树",int(dr_regressor.predict([input_data_encoded])[0]))